/*
 * @Author: adolphus adolphus520@163.com
 * @Date: 2022-11-20 00:25:46
 * @LastEditors: 姚杰鸿
 * @LastEditTime: 2024-11-11 14:26:15
 * @Description: file content
 */
import { InjectionKey } from "vue";
import { Locale, localeInfoList } from "./locale_info";
import * as vars from "@/lib/vars";
import { useStorage } from "@vueuse/core";
import { useStore as baseUseStore, createStore, Store } from "vuex";

export const STORE_STATE = "STATE";

export const changeLang = "changeLang";
export const changeToken = "changeToken";
export const initCurUser = "initCurUser";
export const initMenuItems = "initMenuItems";
export const localStore = "localStore";

//为store state声明类型
export interface State {
  locale: string;
  user: vars.User | null;
  token: string;
  count: number;
  localeInfoList: Locale[];
  menus: vars.menuItem[] | null;
}

//定义 injection key
export const key: InjectionKey<Store<State>> = Symbol();

//导出store模块
export const store = createStore<State>({
  state: {
    locale: "zh",
    user: null,
    token: "",
    count: 0,
    localeInfoList: localeInfoList,
    menus: null,
  },
  getters: {
    locale(state) {
      return useStorage(STORE_STATE, state).value.locale;
    },
    getCurUser: (state): vars.User | null => {
      return useStorage(STORE_STATE, state).value.user;
    },
    getMenus: (state) => {
      console.log(useStorage(STORE_STATE, state).value.menus);
      return useStorage(STORE_STATE, state).value.menus;
    },
    getToken: (state) => {
      return useStorage(STORE_STATE, state).value.token;
    },
  },
  mutations: {
    changeLang(state, payload) {
      useStorage(STORE_STATE, state).value.locale = payload;
    },
    initCurUser(state, user: vars.User) {
      useStorage(STORE_STATE, state).value.user = user;
    },
    initMenuItems(state, menuItems) {
      useStorage(STORE_STATE, state).value.menus = menuItems;
    },
    changeToken(state, payload) {
      useStorage(STORE_STATE, state).value.token = payload;
    },
    localStore(state) {
      useStorage(STORE_STATE, state);
      /*const info = useStorage(STORE_STATE, "");
      console.log("info >>> ", info.value);
      if (info) {
        const _state: State = JSON.parse(info.value);
        if (_state) {
          state.locale = _state.locale;
          state.user = _state.user;
          state.menus = _state.menus;
          state.token = _state.token;
        }
      }*/
    },
  },
  actions: {
    async initMenuItems(ctx) {},
  },
});

export function useStore() {
  return baseUseStore(key);
}
